﻿using Kinlo.Entitys;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using UIWindows.Models;
using UIWindows.Models.Homes;
using UIWindows.Models.Interact;
using UIWindows.Tools.Helper;
using XingLucifer.IBase.Enums;
using XingLucifer.IBase.Models;

namespace UIWindows.GlobalStatics
{
    /// <summary>
    /// 全局临时变量----作为各个地方过度使用的不保存
    /// </summary>
    [Attributes.Singleton]
    public class TemporaryStatic : Domains.ViewModelBase
    {
        #region 单项通知

        private bool _isRunStatus;
        /// <summary>
        /// 设备是否在运行
        /// </summary>
        public bool IsRunStatus
        {
            get { return _isRunStatus; }
            set { SetProperty(ref _isRunStatus, value); }
        }
        /// <summary>
        /// 厂商名称
        /// </summary>
        public string Mes_AccountDep { get; set; } = string.Empty;//厂商名称
        /// <summary>
        /// 账号
        /// </summary>
        public string Mes_Account { get; set; } = string.Empty;//账号
        /// <summary>
        /// 账户名
        /// </summary>
        public string Mes_AccountName { get; set; } = string.Empty;//账户名
        /// <summary>
        /// 联系人
        /// </summary>
        public string Mes_AccountUser { get; set; } = string.Empty;//联系人
        /// <summary>
        /// 联系方式
        /// </summary>
        public string Mes_AccountTel { get; set; } = string.Empty;//联系方式
        /// <summary>
        /// 分钟产量
        /// </summary>

        public int MinuteProduction = 0;

        /// <summary>
        /// 小时产量
        /// </summary>
        public int HourProduction = 0;

        /// <summary>
        /// 小时NG数量
        /// </summary>
        public int HourNGCount = 0;

        /// <summary>
        /// 每小时报警详细
        /// </summary>
        public List<Dictionary<string,object>> WarningList = new List<Dictionary<string, object>>();

        /// <summary>
        /// 报警开始时间记录
        /// </summary>
        public Dictionary<string, DateTime> WarningStaTimeDataList = new Dictionary<string, DateTime>();


        public List<ProductionData> EntityCache { get; set; }
        private Dictionary<string, int> _devicestatus;
        public Dictionary<string, int> DeviceStatus { get => _devicestatus; }
        #endregion

        #region 双向绑定
        private Visibility _isExcision = Visibility.Collapsed;

        public Visibility IsExcision
        {
            get { return _isExcision; }
            set { SetProperty(ref _isExcision, value); }
        }

        private bool _notificationRefresh;
        /// <summary>
        /// 通知刷新
        /// </summary>
        public bool NotificationRefresh
        {
            get { return _notificationRefresh; }
            set { SetProperty(ref _notificationRefresh, value); }
        }

        private double _injectionVolume;
        /// <summary>
        /// 注液量标准
        /// </summary>
        public double InjectionVolume
        {
            get { return _injectionVolume; }
            set { SetProperty(ref _injectionVolume, value); }
        }
        private double _injectionVolumeUP;
        /// <summary>
        /// 注液量上限
        /// </summary>
        public double InjectionVolumeUP
        {
            get { return _injectionVolumeUP; }
            set { SetProperty(ref _injectionVolumeUP, value); }
        }
        private double _injectionVolumeLower;
        /// <summary>
        /// 注液量下限
        /// </summary>
        public double InjectionVolumeLower
        {
            get { return _injectionVolumeLower; }
            set { SetProperty(ref _injectionVolumeLower, value); }
        }
        #endregion
        public Dictionary<MachineInfoTypes,List<PlcAlarmDataModel>> PLCAlarmList { get; set; }

        /// <summary>
        /// 装盘拆盘
        /// </summary>
        public Dictionary<ScanPositionType, List<PlcAlarmDataModel>> PLCAlarmList2 { get; set; }
        public bool Is_Mes_Login { get; set; }
        public ObservableCollection<LinkStatusModel> LinkList { get; set; }
        public ObservableCollection<PLCResectionModel> ExcisionList { get; set; }


        public ObservableCollection<CollectionItems> mesCollectionItemsTemporary { get; set; }

        public TemporaryStatic()
        {

            mesCollectionItemsTemporary = new ObservableCollection<CollectionItems>();

            foreach (MachineInfoTypes type in Enum.GetValues(typeof(MachineInfoTypes)))
            {
                CollectionItems item = new CollectionItems
                {
                    // 在这里设置你的模型的属性
                    MachineStatus="6",
                    PutIntoNumber = 0,
                    QualifiedNumber = 0,
                    UnqualifiedNumber = 0,

                };

                mesCollectionItemsTemporary.Add(item);
            }


            EntityCache = new List<ProductionData>();
            _devicestatus = new Dictionary<string, int>();
            LinkList = new ObservableCollection<LinkStatusModel>()
            {
                new LinkStatusModel(){ 
                    ServiceName = "MES状态",
                    Status = false,
                },
                new LinkStatusModel(){ 
                    ServiceName = "上位机状态",
                    Status = false,
                },
                new LinkStatusModel()
                {
                    ServiceName = "设备状态",
                    Status = true,
                },
            };
            ExcisionList = new ObservableCollection<PLCResectionModel>();

            PLCAlarmList = new Dictionary<MachineInfoTypes, List<PlcAlarmDataModel>>();
            PLCAlarmList2 = new Dictionary<ScanPositionType, List<PlcAlarmDataModel>>();
            if (!Directory.Exists(".\\PLCAlarm")) { Directory.CreateDirectory(".\\PLCAlarm"); }


            // 获取目录下的所有 xls 文件
            string[] xlsFiles = Directory.GetFiles(".\\PLCAlarm", "*.xls");

            // 检查是否成功获取文件
            if (xlsFiles.Length == 0)
            {
                return;
            }
            try
            {
                //// 遍历枚举值
                foreach (MachineInfoTypes machineInfoType in Enum.GetValues(typeof(MachineInfoTypes)))
                {
                    // 根据枚举值生成对应的字符串
                    string machineInfoTypeString = machineInfoType.ToString();

                    // 在 xls 文件中筛选包含当前枚举值字符串的文件

                    var matchingFilePath = xlsFiles.FirstOrDefault(file => Path.GetFileNameWithoutExtension(file).Contains(machineInfoTypeString));

                    if (matchingFilePath != null)
                    {
                        var data = ParseExcel(matchingFilePath);
                        if (data != null)
                        {
                            PLCAlarmList.Add(machineInfoType, data);
                            //$"{machineInfoTypeString}设备报警信息加载成功".RunLog(MessageLevelType.成功);
                        }
                    }else
                    {
                        Console.WriteLine("");
                    }
                    //matchingFilePath = ".\\PLCAlarm\\" + matchingFilePath;
                    
                }

                
                //foreach (ScanPositionType scanPositionType in Enum.GetValues(typeof(ScanPositionType)))
                //{
                //    // 根据枚举值生成对应的字符串
                //    int scanPositionTypeString = (int)scanPositionType;

                //    // 在 xls 文件中筛选包含当前枚举值字符串的文件

                //    var matchingFilePath = xlsFiles.FirstOrDefault(file => Path.GetFileNameWithoutExtension(file).Contains($"装盘机{scanPositionTypeString}")
                //    || Path.GetFileNameWithoutExtension(file).Contains($"拆盘机{scanPositionTypeString}"));

                //    if (matchingFilePath != null)
                //    {
                //        var data = ParseExcel(matchingFilePath);
                //        if (data != null)
                //        {
                //            PLCAlarmList2.Add(scanPositionType, data);
                //            //$"{machineInfoTypeString}设备报警信息加载成功".RunLog(MessageLevelType.成功);
                //        }
                //    }else
                //    {
                //        Console.WriteLine("");
                //    }
                //    //matchingFilePath = ".\\PLCAlarm\\" + matchingFilePath;
                    
                //}



            }catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
          
        }

        public List<PlcAlarmDataModel> ParseExcel(string filePath)
        {
            try
            {
                List<PlcAlarmDataModel> alarmInfos = new List<PlcAlarmDataModel>();
                // 获取当前目录
                string currentDirectory = Directory.GetCurrentDirectory();

                //// 文件夹名
                //string folderName = "AlarmInfoConfig";

                //// 拼接文件路径
                //string filePath = Path.Combine(currentDirectory, folderName, fileName);

                using (FileStream file = new FileStream(filePath, FileMode.Open, FileAccess.Read))
                {
                    //IWorkbook workbook = new XSSFWorkbook(file);

                    HSSFWorkbook workbook = new HSSFWorkbook(file);
                    ISheet sheet = workbook.GetSheetAt(0); // 假设数据在第一个工作表中

                    int i = 1;
                    // 假设列标题为：类别、设备类型 (读取地址)、地址 (读取地址)、内容、报警条件
                    int categoryIndex = -1;
                    int deviceTypeIndex = -1;
                    int alarmAddressIndex = -1;
                    int alarmContentIndex = -1;
                    int alarmconditionIndex = -1;


                    // 获取第二行作为列标题行
                    IRow headerRow = sheet.GetRow(1);
                    if (headerRow != null)
                    {
                        for (int cellIndex = 0; cellIndex < headerRow.LastCellNum; cellIndex++)
                        {
                            var cellValue = headerRow.GetCell(cellIndex)?.StringCellValue;

                            // 根据列标题找到对应的索引
                            switch (cellValue)
                            {
                                case "类别":
                                    categoryIndex = cellIndex;
                                    break;
                                case "设备类型 (读取地址)":
                                    deviceTypeIndex = cellIndex;
                                    break;
                                case "地址 (读取地址)":
                                    alarmAddressIndex = cellIndex;
                                    break;
                                case "内容":
                                    alarmContentIndex = cellIndex;
                                    break;
                                case "触发条件":
                                    alarmconditionIndex = cellIndex;
                                    break;
                            }
                        }
                    }

                    // 如果所有索引都找到了，则进行数据读取
                    if (categoryIndex >= 0 && deviceTypeIndex >= 0 && alarmAddressIndex >= 0 && alarmContentIndex >= 0 && alarmconditionIndex >= 0)
                    {
                        for (int rowIndex = 1; rowIndex <= sheet.LastRowNum; rowIndex++)
                        {
                            IRow row = sheet.GetRow(rowIndex);

                            // 根据索引读取对应的数据
                            string category = row.GetCell(categoryIndex)?.StringCellValue;
                            string deviceType = row.GetCell(deviceTypeIndex)?.StringCellValue;
                            string alarmAddress = row.GetCell(alarmAddressIndex)?.StringCellValue;
                            string alarmContent = row.GetCell(alarmContentIndex)?.StringCellValue;
                            string alarmcondition = row.GetCell(alarmconditionIndex)?.StringCellValue;
                            if (category != null && category.Contains("0"))
                            {
                                alarmInfos.Add(new PlcAlarmDataModel
                                {
                                    Id = i++,
                                    DeviceType = deviceType,
                                    AlarmAddress = deviceType.Replace("_Bit", "") + alarmAddress,
                                    AlarmContent = alarmContent,
                                    Alarmcondition = alarmcondition.Contains("1") ? 1 : 0,
                                });
                            }
                        }
                    }
                }
                return alarmInfos;
            }
            catch (Exception ex)
            {
                // 在这里处理异常，您可以使用消息框或记录到日志文件中
                System.Windows.MessageBox.Show("加载报警信息时发生错误：" + ex.Message, "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                return null;
            }


        }

        /// <summary>
        /// 获取单元格类型
        /// </summary>
        /// <param name="cell">目标单元格</param>
        /// <returns></returns>
        private static object GetValueType(ICell cell)
        {
            if (cell == null)
                return null;
            switch (cell.CellType)
            {
                case CellType.Blank:
                    return null;
                case CellType.Boolean:
                    return cell.BooleanCellValue;
                case CellType.Numeric:
                    return cell.NumericCellValue;
                case CellType.String:
                    return cell.StringCellValue;
                case CellType.Error:
                    return cell.ErrorCellValue;
                case CellType.Formula:
                default:
                    return "=" + cell.CellFormula;
            }
        }
    }


    public class CollectionItems: Domains.ViewModelBase
    {
        private string _machineStatus;
     
        public string MachineStatus
        {
            get { return _machineStatus; }
            set { SetProperty(ref _machineStatus, value); }
        }
        private int _putIntoNumber;
     
        public int PutIntoNumber
        {
            get { return _putIntoNumber; }
            set { SetProperty(ref _putIntoNumber, value); }
        }
        private int _qualifiedNumber;
     
        public int QualifiedNumber
        {
            get { return _qualifiedNumber; }
            set { SetProperty(ref _qualifiedNumber, value); }
        }
        
        private int _unqualifiedNumber;
     
        public int UnqualifiedNumber
        {
            get { return _unqualifiedNumber; }
            set { SetProperty(ref _unqualifiedNumber, value); }
        }



        private int _inCount;
     
        public int InCount
        {
            get { return _inCount; }
            set { SetProperty(ref _inCount, value); }
        }
        private int _okCount;
     
        public int OKCount
        {
            get { return _okCount; }
            set { SetProperty(ref _okCount, value); }
        }
        
        private int _ngCount;
     
        public int NGCount
        {
            get { return _ngCount; }
            set { SetProperty(ref _ngCount, value); }
        }
        
        private string _trayBarcode;
     
        public string TrayBarcode
        {
            get { return _trayBarcode; }
            set { SetProperty(ref _trayBarcode, value); }
        }


    }
}
